package com.jenkins.test.base;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.jenkins.test.response.Result;
import com.jenkins.test.response.ResultPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @version V0.0.1
 * @ClassName: {@link BaseController}
 * @Description: 基本的Controller操作
 * @author: Lanzhou
 * @date: 2021/6/10 22:48
 * @Copyright:2019 All rights reserved.
 * 注意：本内容仅限于本人开发与维护，禁止外泄以及用于其他的商业目
 */
@SuppressWarnings("all")
public abstract class BaseController<D, S extends IBaseService<D>> {

    @Autowired
    protected S service;

    /**
     * 分页获取书数据
     *
     * @param pageIndex 当前页
     * @param pageSize  每页多少条数据
     * @return {@link ResultPage}
     */
    @GetMapping("/page")
    public ResultPage<D> page(Long pageIndex, Long pageSize) {
        Page<D> page = null;
        if (pageIndex == null || pageSize == null) {
            page = new Page<>();
        } else {
            page = new Page<>(pageIndex, pageSize);
        }
        IPage<D> iPage = service.page(page);
        return new ResultPage<>(iPage);
    }

    /**
     * 获取所有书数据
     *
     * @return {@link Result}
     */
    @GetMapping("/list")
    public Result<List<D>> list() {
        return Result.success(service.list());
    }


    /**
     * 根据Id获取当前书数据
     *
     * @return {@link Result}
     */
    @GetMapping("/{id}")
    public Result<D> getById(@PathVariable("id") Long id) {
        return Result.success(service.getById(id));
    }


    /**
     * 新增书数据
     *
     * @return {@link Result}
     */
    @PostMapping
    public Result<D> add(@RequestBody D entity) {
        boolean save = service.save(entity);
        return save ? Result.success(entity) : Result.fail("新增失败");
    }


    /**
     * 修改书数据
     *
     * @return {@link Result}
     */
    @PutMapping
    public Result<D> update(@RequestBody D entity) {
        boolean update = service.updateById(entity);
        return update ? Result.success(entity) : Result.fail("新增失败");
    }

    /**
     * 删除书数据
     *
     * @return {@link Result}
     */
    @DeleteMapping
    public Result<D> delete(@RequestBody String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        boolean remove = service.removeByIds(idList);
        return remove ? Result.success() : Result.fail();
    }

}
